package com.clei.dto.db;

import com.clei.utils.CollectionUtil;
import com.clei.utils.StringUtil;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * mysql 表字段属性
 *
 * @author Y
 * @date 2024-01-09
 */
public class ColumnProperty {
    /**
     * 数据库 列名
     */
    private final String columnName;

    /**
     * java 属性名
     */
    private final String propertyName;

    /**
     * java 属性类型
     */
    private final String propertyType;

    /**
     * java 简单属性类型
     */
    private final String propertySimpleType;

    /**
     * comment
     */
    private final String columnComment;

    public ColumnProperty(String columnName, String propertyType, String columnComment) {
        this.columnName = columnName.toLowerCase();
        this.propertyName = StringUtil.snake2Camel(columnName);
        this.columnComment = columnComment;
        this.propertyType = propertyType;
        this.propertySimpleType = this.propertyType.substring(this.propertyType.lastIndexOf('.') + 1);
    }

    /**
     * columnPropertyList
     *
     * @param columnList    columnList
     * @param typeConverter typeConverter
     * @return list
     */
    public static List<ColumnProperty> columnPropertyList(List<Map<String, String>> columnList, Function<String, String> typeConverter) {
        if (CollectionUtil.isEmpty(columnList)) {
            return Collections.emptyList();
        }
        // 保证 column key对应
        // 导出本地库8.0.28的时候 columnKey是大写的
        // 导出服务器库5.7.44的时候 columnKey是小写的
        Map<String, String> map1 = columnList.get(0);
        Map<String, String> keyMap = new HashMap<>(map1.size());
        if (CollectionUtil.isNotEmpty(columnList)) {
            map1.forEach((k, v) -> keyMap.put(k.toUpperCase(), k));
        }
        String cn = keyMap.get("COLUMN_NAME");
        String ct = keyMap.get("COLUMN_TYPE");
        String cc = keyMap.get("COLUMN_COMMENT");
        // 分隔 转换
        return columnList.stream()
                .map(map -> {
                    String columnName = map.get(cn);
                    String columnType = map.get(ct);
                    String columnComment = map.get(cc);
                    return new ColumnProperty(columnName, typeConverter.apply(columnType), columnComment);
                }).collect(Collectors.toList());
    }

    public String getColumnName() {
        return columnName;
    }

    public String getPropertyName() {
        return propertyName;
    }

    public String getColumnComment() {
        return columnComment;
    }

    public String getPropertyType() {
        return propertyType;
    }

    public String getPropertySimpleType() {
        return propertySimpleType;
    }
}